package router

import (
	"bookStore/global"
	"bookStore/util/cookieUtils"
	"bookStore/util/stringUtils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

// 用户登录拦截器
func UserLoginInterceptor(context *gin.Context) {
	path := context.Request.URL.Path
	if path == "/login" {
		context.Next()
	} else {
		cookieCheck(context)
	}
}

// cookie检查
func cookieCheck(context *gin.Context) {
	cookie, err := context.Cookie(global.CookieKey)
	if err != nil {
		context.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": err.Error(), "code": http.StatusUnauthorized})
	} else if stringUtils.IsBlank(cookie) {
		context.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "无Cookie信息", "code": http.StatusUnauthorized})
	} else {
		cookieValueCheck(context, cookie)
	}
}

// cookie中的value检查
func cookieValueCheck(context *gin.Context, cookie string) {
	cookieTime, userId, err := cookieUtils.ResolveCookie(cookie)
	if err != nil {
		context.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"message": err.Error(), "code": http.StatusBadRequest})
	} else {
		cookieTimeCheck(context, cookieTime)
		cookieUserCheck(context, userId)
	}
}

// cookie中value里存放的时间检查
func cookieTimeCheck(context *gin.Context, cookieTime string) {
	oldTime, errTime := time.ParseInLocation("2006-01-02 15:04:05", cookieTime, time.Local)
	if errTime != nil {
		context.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"message": "cookie中时间信息错误", "code": http.StatusBadRequest})
	} else {
		if time.Now().Sub(oldTime).Milliseconds() > 24*60*60*1000 {
			context.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "cookie已失效", "code": http.StatusUnauthorized})
		}
	}
}

// cookie中value里存放的用户id检查
func cookieUserCheck(context *gin.Context, userId string) {
	id, err := strconv.ParseInt(userId, 10, 64)
	if err != nil {
		context.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"message": "cookie中用户信息错误", "code": http.StatusBadRequest})
	} else {
		context.Set(global.UserId, id)
		context.Next()
	}
}
